package message;

import lombok.extern.java.Log;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.util.StringUtils;

import javax.jms.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

/**
 * 发布订阅 模式  申请应答方
 *
 * @author Guojt
 * @date 2024/11/6 7:56
 */
@Log
public class TLender {
    private static String USERNAME = ActiveMQConnection.DEFAULT_USER;
    private static String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
    private static String BROKER = ActiveMQConnection.DEFAULT_BROKER_URL;
    private TopicConnection tConnect = null;
    private TopicSession tSession = null;
    private Topic topic = null;

    public TLender(String topiccf, String topicName) {
        try {
            TopicConnectionFactory tcf = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKER);
            tConnect = tcf.createTopicConnection();
            tSession = tConnect.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
            topic = tSession.createTopic(topicName);

            tConnect.start();
        } catch (JMSException e) {
            throw new RuntimeException(e);
        }
    }

    private void publishRate(double newRate) {
        try {
            BytesMessage message = tSession.createBytesMessage();
            message.writeDouble(newRate);

            TopicPublisher publisher = tSession.createPublisher(topic);
            publisher.publish(message);
        } catch (JMSException e) {
            throw new RuntimeException(e);
        }
    }

    private void exit() {
        try {
            tConnect.close();
        } catch (JMSException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        TLender tLender = new TLender("TopicCF", "TLTopic");
        try {
            BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));

            while (true) {
                System.out.println("> ");
                String rate = stdin.readLine();
                if (StringUtils.isEmpty(rate)) {
                    tLender.exit();
                }

                // 解析交易说明
                double newrate = Double.valueOf(rate);
                tLender.publishRate(newrate);
            }
        } catch (Exception e) {
            log.warning(e.getMessage());
        }
    }
}
